#!/usr/bin/env python
# coding=utf8
"""
@summary: 从hadoop上将文件读出来，并且转化region字段；最后发送邮件
@attention: 从hadoop上将文件读出来，并且转化region字段；最后发送邮件
@author: hongxingfan
@since: 2014年8月7日	下午3:36:42
"""
from email.mime.text import MIMEText
import smtplib
import sys
reload(sys)
sys.setdefaultencoding("utf8")
import commands
import datetime
import time
  
def send_mail(mail_host, from_1, to_list, sub, content):  # to_list：收件人；sub：主题；content：邮件内容
	#cbg-data@baidu.com
	msg = MIMEText(content, _subtype = "html", _charset = "utf-8")  # 创建一个实例，这里设置为文本格式邮件
	msg["Subject"] = sub  # 设置主题
	msg["From"] = from_1
	msg["To"] = ";".join(to_list)
	msg["Accept-Language"] = "zh-CN"
	msg["Accept-Charset"] = "ISO-8859-1,utf-8"
	try:
		smtp = smtplib.SMTP()
		smtp.connect(mail_host)
		smtp.sendmail(from_1, to_list, msg.as_string())  # 发送邮件
		smtp.close()
		return True
	except Exception, e:
		print str(e)
		return False

def deal(log_date, dbHandler):
	mail_host = "mail1-in.baidu.com"  # 设置服务器
	from_1 = "noah-autopost@baidu.com"
	to_list = ["fanhongxing@baidu.com","baiyunlong@baidu.com","wangshaoxin@baidu.com","sudongdong@baidu.com","renxiaohu@baidu.com"]
	#to_list = ["fanhongxing@baidu.com"]
	
	message = "<html><body><table border='2'><tr>"
	message += "<td>" + "主机" + "</td>"
	message += "<td>" + "表名" + "</td>"
	message += "<td>" + "日期" + "</td>"
	message += "<td>" + "动作" + "</td>"
	message += "<td>" + "状态" + "</td>"
	message += "<td>" + "数量" + "</td>"
	message += "<td>" + "起始时间" + "</td>"
	message += "<td>" + "结束时间" + "</td>"
	message += "</tr>"

	sql2 = """
	select host,log_name,log_date,action,status,count(distinct local_path) as count,min(begin_time) as begin,max(end_time) as end from pass_data.pass_log 
        where log_date=%s group by host,log_name,log_date,action,status
	order by host,log_name,log_date,action asc, status desc
	"""
	result2 = dbHandler.select(sql2,[log_date])
	old = ""
	for(host,logName,logDate,action,status,count,begin,end) in result2:
		if(old != "" and old != host):
			message += "<tr></tr>"
		old = host
		message += "<tr>"
		message += "<td>" + host  + "</td>"
		message += "<td>" + logName + "</td>"
		message += "<td>" + logDate + "</td>"
		message += "<td>" + action + "</td>"
		message += "<td>" + status + "</td>"
		message += "<td>" + str(count) + "</td>"
		message += "<td>" + str(begin) + "</td>"
		message += "<td>" + str(end) + "</td>"
		message += "</tr>"
	message += "</html>"
	sub = "pass日志 抓取上载明细"
	send_mail(mail_host, from_1, to_list, sub, message)
	return True

if __name__ == "__main__":
	import datetime
	import time
	log_date = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y%m%d")
	if(len(sys.argv) == 2):
		log_date = sys.argv[1]
	
	sys.path.append(".")
	from DBUtils import MySQLDB
	dbHandler = MySQLDB("10.195.82.35","root","mysql",3306,"utf8")
	
	sql1 = """
		select count(distinct local_path) as count from pass_data.pass_log where log_date=%s
		"""
	result1 = dbHandler.select(sql1,[log_date])
	tryTime = 0
	while(result1 is None or len(result1) < 1 or result1[0][0] < 1300):
		if(tryTime < 120):
			tryTime += 1
			time.sleep(600)
			result1 = dbHandler.select(sql1,[log_date])
			continue
		else:
			break

	deal(log_date, dbHandler)
	dbHandler.close()

